package com.zhongxi.guoyuan.fragment;


import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseFragment;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.UpdateResult;
import com.zhongxi.guoyuan.entity.consumerYield.TodayConsumerYield;
import com.zhongxi.guoyuan.entity.user.OnLineCodeResult;
import com.zhongxi.guoyuan.entity.user.TodayHomeEarnResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.ClearCacheUtils;
import com.zhongxi.guoyuan.utils.DataUtil;
import com.zhongxi.guoyuan.utils.SpUtils;
import com.zhongxi.guoyuan.utils.UiUtils;
import com.zhongxi.guoyuan.view.ConsumerLoveYieldActivity;
import com.zhongxi.guoyuan.view.MainActivity;
import com.zhongxi.guoyuan.view.MainHomeActivity;
import com.zhongxi.guoyuan.view.beanExchange.PersonExchangeActivity;
import com.zhongxi.guoyuan.view.personalCenter.BeanDynamicActivity;
import com.zhongxi.guoyuan.view.personalCenter.BeautifulStoreOrderActivity;
import com.zhongxi.guoyuan.view.personalCenter.HasConsumeActivity;
import com.zhongxi.guoyuan.view.personalCenter.LogisticsSearchActivity;
import com.zhongxi.guoyuan.view.personalCenter.NewCollectActivity;
import com.zhongxi.guoyuan.view.personalCenter.OffLineConsumeListActivity;
import com.zhongxi.guoyuan.view.personalCenter.PersonAboutUsActivity;
import com.zhongxi.guoyuan.view.personalCenter.RewardCoinOrderActivity;
import com.zhongxi.guoyuan.view.personalCenter.SystemMessageActivity;
import com.zhongxi.guoyuan.view.personalCenter.WithDrawCashActivity;
import com.zhongxi.guoyuan.view.shopCart.ShoppingCartActivity;
import com.zhongxi.guoyuan.view.user.MyDividendActivity;
import com.zhongxi.guoyuan.view.user.UserInfoSettingActivity;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * A simple {@link Fragment} subclass.
 */
public class MainPersonFragment extends BaseFragment {

    public static final int REQUESTNOPAY = 1234;
    private static final int REQUESTSETTING = 9969;
    @Bind(R.id.person_beauty)
    RelativeLayout personBeauty;
    @Bind(R.id.person_reward)
    RelativeLayout personReward;
    @Bind(R.id.person_exchange)
    RelativeLayout personExchagne;
    @Bind(R.id.person_cart)
    RelativeLayout personCart;
    @Bind(R.id.person_offline_store)
    RelativeLayout personOfflineStore;
    @Bind(R.id.person_withdraw)
    RelativeLayout personWithdraw;
    @Bind(R.id.person_collect)
    RelativeLayout personCollect;
    @Bind(R.id.person_record)
    RelativeLayout personRecord;
    @Bind(R.id.person_bean_dynamic)
    RelativeLayout personBeanDynamic;
    @Bind(R.id.person_setting)
    RelativeLayout personSetting;
    @Bind(R.id.person_dynamic)
    RelativeLayout personDynamic;
    @Bind(R.id.person_delivery)
    RelativeLayout personDelivery;
    @Bind(R.id.person_cleanCache)
    RelativeLayout personCleanCache;
    @Bind(R.id.person_update)
    RelativeLayout personUpdate;
    @Bind(R.id.person_exit)
    RelativeLayout personExit;
    @Bind(R.id.ivBack)
    ImageView ivBack;
    @Bind(R.id.cachesize)
    TextView cachesize;
    @Bind(R.id.ll_person_phone)
    LinearLayout mllPhone;
    @Bind(R.id.userphone_tip)
    TextView userphone_tip;
    @Bind(R.id.person_yesterday_earn)
    TextView yesterdayEarn;
    @Bind(R.id.person_yesterday_redearn)
    TextView yesterdayRedEarn;
    @Bind(R.id.person_offline_earn)
    RelativeLayout offlineEarn;
    @Bind(R.id.person_offline_redearn)
    RelativeLayout offlineRedEarn;


    private TextView tvUserName;
    private TextView tvUserPhone;
    private TextView tvBonusPoint;
    private TextView tvIdentify;
    private ImageView ivUserHead;
    private String type;
    private UpdateResult result;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View mInflate = inflater.inflate(R.layout.activity_main_person, container, false);
        ButterKnife.bind(this, mInflate);
        return mInflate;
    }

    @Override
    protected void initView() {
        super.initView();
        initTitle();
        tvTitle.setText("个人中心");
        tvUserName = (TextView) getView().findViewById(R.id.tvUserName);
        tvUserPhone = (TextView) getView().findViewById(R.id.tvUserPhone);
        ivUserHead = (ImageView) getView().findViewById(R.id.ivUserHead);
        tvBonusPoint = (TextView) getView().findViewById(R.id.tvBonusPoint);  //红豆
        tvIdentify = (TextView) getView().findViewById(R.id.tvIdentify);  //红豆

    }

    @Override
    protected void initData() {
        super.initData();
        if (TextUtils.isEmpty(MyApplication.getInstance().getInnerCurrency())) {
            tvIdentify.setText("0 美豆");
        } else {
            tvIdentify.setText(MyApplication.getInstance().getInnerCurrency() + " 美豆");
        }
        if (TextUtils.isEmpty(MyApplication.getInstance().getHdCurrency())) {
            tvBonusPoint.setText("0 红豆");
        } else {
            tvBonusPoint.setText(DataUtil.formatDataSixPoint(MyApplication.getInstance().getHdCurrency()) + " 个");
        }
        if (null != MyApplication.getInstance().getUserName() && !"".equals(MyApplication.getInstance().getUserName())) {
            tvUserName.setText(MyApplication.getInstance().getUserName());
        } else {
            tvUserName.setText(R.string.app_name);
        }

        if (!TextUtils.isEmpty(MyApplication.getInstance().getPhone()) && !TextUtils.isEmpty(MyApplication.getInstance().getAppOpenid())) {
            userphone_tip.setText("手机号：");
            tvUserPhone.setText(MyApplication.getInstance().getPhone());

            Glide.with(context)
                    .load(Url.BASE_URL + MyApplication.getInstance().getAvatar())
                    .placeholder(R.mipmap.logo)
                    .into(ivUserHead);
        } else if (TextUtils.isEmpty(MyApplication.getInstance().getPhone())) {
            userphone_tip.setText("微信号：");
            tvUserPhone.setText(MyApplication.getInstance().getWxName());
            Glide.with(context)
                    .load(MyApplication.getInstance().getWxIcon())
                    .placeholder(R.mipmap.logo)
                    .into(ivUserHead);
        } else if (TextUtils.isEmpty(MyApplication.getInstance().getAppOpenid())) {
            userphone_tip.setText("手机号：");
            tvUserPhone.setText(MyApplication.getInstance().getPhone());

            Glide.with(context)
                    .load(Url.BASE_URL + MyApplication.getInstance().getAvatar())
                    .placeholder(R.mipmap.logo)
                    .into(ivUserHead);
        }

        try {
            if (ClearCacheUtils.getTotalCacheSize(context) != null) {
                cachesize.setText(ClearCacheUtils.getTotalCacheSize(context).toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        getConsumegains();
    }

    /**
     * 获取昨日消费现金收益
     */
    private void getConsumegains() {
        type = "todayConsuem";
        getServer(Url.CONSUMER_TODAY_YIELD, null, "", false, null, "get");
    }

    @OnClick({R.id.ivBack, R.id.person_beauty, R.id.person_reward, R.id.person_offline_earn, R.id.person_offline_redearn,
            R.id.person_bean_dynamic, R.id.person_offline_store, R.id.person_cart, R.id.person_withdraw,
            R.id.person_collect, R.id.person_record, R.id.person_setting, R.id.person_dynamic, R.id.person_delivery,
            R.id.person_cleanCache, R.id.person_update, R.id.person_exit, R.id.person_exchange})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ivBack:
                getActivity().finish();
                break;
            case R.id.person_beauty:
                Intent intentNopay = new Intent(context, BeautifulStoreOrderActivity.class);
                startActivityForResult(intentNopay, REQUESTNOPAY);
                break;
            case R.id.person_reward:
                startAct(RewardCoinOrderActivity.class);//超市订单列表
                break;
            case R.id.person_exchange:
                startAct(PersonExchangeActivity.class);
                break;
            case R.id.person_offline_store:
                startAct(OffLineConsumeListActivity.class);  // 线下消费清单
                break;
            case R.id.person_offline_earn:
//                if (MyApplication.getInstance().isbeneficiary() || MyApplication.getInstance().isShareHolders()) {
                startAct(MyDividendActivity.class);
//                } else {
//                    type = "online";
//                    getServer(Url.ONLINE_CONSUME, null, "", false, null, "get");
//                }
                break;
            case R.id.person_offline_redearn:
                startAct(ConsumerLoveYieldActivity.class);
                break;
            case R.id.person_cart:
                startActivity(new Intent(context, ShoppingCartActivity.class));
                break;
            case R.id.person_withdraw:
                startAct(WithDrawCashActivity.class);//提现助手
                break;
            case R.id.person_collect:
//                startAct(MyCollectionActivity.class);//收藏
                startAct(NewCollectActivity.class);//收藏
                break;
            case R.id.person_record:  //消费记录
//                startAct(HasConsumeHomeActivity.class);
                Intent intent1 = new Intent(context, HasConsumeActivity.class);
                intent1.putExtra("index", 1);
                startActivity(intent1);
                break;
            case R.id.person_bean_dynamic://豆豆动态
                startAct(BeanDynamicActivity.class);
                break;
            case R.id.person_setting:
                startActivityForResult(new Intent(context, UserInfoSettingActivity.class), REQUESTSETTING);
                break;
            case R.id.person_dynamic://系统消息
                startAct(SystemMessageActivity.class);
                break;
            case R.id.person_delivery://快递查询
                startAct(LogisticsSearchActivity.class);
                break;
            case R.id.person_cleanCache:
                ClearCacheUtils.clearAllCache(context);
                cachesize.setText("0KB");
                showShortToast("清理完成");
                break;
            case R.id.person_update://关于我们
                startAct(PersonAboutUsActivity.class);
                break;
            case R.id.person_exit:
                getLogout();
                if (null != MyApplication.getInstance().getUserId() || !"".equals(MyApplication.getInstance().getUserId())) {
                    MyApplication.getInstance().sharedPrefrences.edit().putString("phone", "").commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("userid", "").commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("username", "").commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("shopname", "").commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("rmb", "").commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("silver", "").commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("inner", "").commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("hd", "").commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("num", "").commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("avatar", "").commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putBoolean("shareHolder", false).commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putBoolean("privilege", false).commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("avatar", "").commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("rewardName", "").commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("rewardUserphone", "").commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("rewardAddress", "").commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("rewardAddressid", "").commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putBoolean("beneficiary", false).commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putBoolean("merchants", false).commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("appopenid", "").commit();
                    SpUtils.getInstance().saveSp("shopid", "");
                    SpUtils.getInstance().saveSp("mdffline", "");
                    SpUtils.getInstance().saveSp("orderid", "");
                    startAct(MainHomeActivity.class);
                    getActivity().finish();
                }
                break;

        }
    }

    private void getLogout() {
        type = "logout";
        getServer(Url.LOGOUT, null, "", false, null, "get");
    }


    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        if ("todayConsuem".equals(type)) {
            TodayConsumerYield todayConsumerYield = gson.fromJson(response, TodayConsumerYield.class);
            MyApplication.getInstance().setSpValue(todayConsumerYield.getSafeobj());
            if (null != todayConsumerYield.getPrevDayGains() && !"".equals(todayConsumerYield.getPrevDayGains())) {
                yesterdayRedEarn.setText(todayConsumerYield.getPrevDayGains() + " 元");
            } else {
                yesterdayRedEarn.setText("0 元");
            }
            getSharesgains();
        } else if ("today".equals(type)) {
            TodayHomeEarnResult result = gson.fromJson(response, TodayHomeEarnResult.class);
            MyApplication.getInstance().setSpValue(result.getSafeobj());
            if (null != result.getRecode() && result.getRecode().size() > 0) {
                yesterdayEarn.setText(DataUtil.formatDataFivePoint(result.getRecode().get(0).getSharesgains()) + "元");
            } else {
                yesterdayEarn.setText("0 元");
            }
        } else if ("logout".equals(type)) {
            BaseResponse mBaseResponse = gson.fromJson(response, BaseResponse.class);
            MyApplication.getInstance().setSpValue(mBaseResponse.getSafeobj());
        }
    }

    /**
     * 获取昨日股份收益
     */
    private void getSharesgains() {
        type = "today";
        getServer(Url.MY_TODAY_EARNINGS, null, "", false, null, "get");
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        BaseResponse baseResponse = gson.fromJson(response, BaseResponse.class);
        if (null != baseResponse.getSafeobj() && !"".equals(baseResponse.getSafeobj())) {
            MyApplication.getInstance().setSpValue(baseResponse.getSafeobj());
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUESTSETTING) {
            Glide.with(context)
                    .load(Url.BASE_URL + MyApplication.getInstance().getAvatar())
                    .placeholder(R.mipmap.logo)
                    .into(ivUserHead);
            if (null != MyApplication.getInstance().getUserName() && !"".equals(MyApplication.getInstance().getUserName())) {
                tvUserName.setText(MyApplication.getInstance().getUserName());
            } else {
                tvUserName.setText(R.string.app_name);
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

}
